#include <stdint.h>
#include "lgt8f690a.h"

static uint16_t evt_in_cnt = 0;
static uint16_t evt_in_cnt_last = 0;
static uint16_t evt_out;

void notifyper32ms(void)
{
	++evt_in_cnt;
	evt_out = evt_in_cnt ^ evt_in_cnt_last;
	evt_in_cnt_last = evt_in_cnt;
}

uint8_t getEvent(void)
{
	return (uint8_t)evt_out;
}

void clrEvent(uint8_t bitmask)
{
	evt_out &= (uint16_t)0xFF00 |  (uint16_t)(~bitmask);
}

uint16_t getEvent16(void)
{
	return evt_out;
}

void clrEvent16(uint16_t bitmask)
{
	evt_out &= (~bitmask);
}
/*
int8_t getRandom(uint8_t range)
{
	uint8_t seed;
	seed = (uint8_t)evt_in_cnt & range;
	if (seed & ((range + 1)>>1))
	{
		seed |= (~range);
	}
	return (int8_t)seed;
}
*/
int8_t rdt[12]={1,0,-1,-2,-3,-2,-1,0,1,2,3,2};
void updater(int8_t * tb, uint8_t len)
{
	uint8_t i;
	int8_t head;
	head = *tb;
	for (i=0; i<len-1; i++){
		*tb = *(tb+1);
		++tb;
	}
	*tb = head;
}
int8_t getRandom7(void)
{
	uint8_t seed;
	int8_t rd;
	seed = (uint8_t)evt_in_cnt & 7;
	rd = rdt[seed];
	updater(rdt,sizeof(rdt));
	return rd;
}